package io.github.wx.web.sys;

import com.jfinal.aop.Duang;
import io.github.wx.common.controller.BaseController;
import io.github.wx.common.shiro.kit.ShiroSessionKit;
import io.github.wx.service.MenuService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;

/**
 * Created by jie on 2017/4/2.
 * 主页跳转
 */
public class IndexController extends BaseController {
    static final MenuService menuService = Duang.duang(MenuService.class);

    public void index() {
        render("index.html");
    }

    /**
     * 首页
     */
    public void home() {
        render("oscpage.html");
    }

    /**
     * 跳转到登录页
     */
    public void login() {
        render("login.html");
    }

    /**
     * 用户登录
     */
    public void userLogin() {
        String username = getPara("username");
        String password = getPara("password");

        Subject currentUser = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
            currentUser.login(token);
            ShiroSessionKit.addSessionRelation();
            renderSuccess();
        } catch (UnknownAccountException exception) {
            renderFailed("账户不存在");
        } catch (IncorrectCredentialsException exception) {
            renderFailed("密码错误");
        } catch (LockedAccountException exception) {
            renderFailed("账号被锁定");
        }
    }

    public void loginOut() {
        ShiroSessionKit.delSessionRelation(getUsername());
        getSubject().logout();
        redirect("/login");
    }

    /**
     * 用户未通过授权
     */
    public void unauthorized() {
        renderText("权限不足");
    }

}